package cn.bdqn.t230.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;

import cn.bdqn.t230.MyBatisUtil;
import cn.bdqn.t230.mapper.UserMapper;
import cn.bdqn.t230.pojo.PageBean;
import cn.bdqn.t230.pojo.User;
import cn.bdqn.t230.util.StringUtils;

public class UserService {
	private UserMapper userMapper = null;
	private SqlSession session = null;
	
	public List<User> findAll(String userName, String userRole) {
		try {
			session = MyBatisUtil.createSession();
			userMapper = session.getMapper(UserMapper.class);
			
			return userMapper.findAll(userName, StringUtils.isEmpty(userRole) ? null : Integer.parseInt(userRole));
		} finally {
			session.close();
		}
	}
	public List<User> findByUser(User user) {
		try {
			session = MyBatisUtil.createSession();
			userMapper = session.getMapper(UserMapper.class);
			
			return userMapper.findByUser(user);
		} finally {
			session.close();
		}
	}
	public List<User> findAll(String userName, String[] userRoles) {
		try {
			session = MyBatisUtil.createSession();
			userMapper = session.getMapper(UserMapper.class);
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("userName", userName);
			params.put("userRoles", userRoles);
			return userMapper.findAllByMap(params);
//			return userMapper.findAllByArray(userName, userRoles);
		} finally {
			session.close();
		}
	}
	public List<User> findByUser(User user, String[] userRoles) {
		return null;
	}
	
	public void findByMap(PageBean<User> pageBean,Map<String, Object> params) {
		
		try {
			session = MyBatisUtil.createSession();
			userMapper = session.getMapper(UserMapper.class);
			int total = userMapper.findAllByMapCount(params);
			pageBean.setTotal(total); //设置总记录数和总页数
			if(pageBean.getPageNo() < 1) pageBean.setPageNo(1);
			if(pageBean.getPageNo()>pageBean.getTotalPages())pageBean.setPageNo(pageBean.getTotalPages());
			params.put("from", (pageBean.getPageNo()-1)*pageBean.getPageSize());
			params.put("pageSize", pageBean.getPageSize());
			List<User> list = userMapper.findAllByMap(params);
			pageBean.setDataList(list);
		} finally {
			session.close();
		}
		
	}
}
